package com.wedimob.slideshare.task.io.network;

import java.net.URL;

import org.jsoup.Connection.Response;

import com.wedimob.slideshare.RuntimeConfig;
import com.wedimob.slideshare.bo.Medium;
import com.wedimob.slideshare.task.PoolExecutor;
import com.wedimob.slideshare.task.Task;

public class TaskMediumWriter extends Task<Medium, Medium> {

    public TaskMediumWriter(PoolExecutor pool, Medium picture, int timeout) {
        super(pool, picture, 0, timeout);
    }

    @Override
    public String toString() {
        return input.getUrl().toString();
    }
    
    static Response UnknownPicture;

    @Override
    public void run() {
        try {
        	System.err.println("TaskMediumWriter url{" + input.getUrl() + "} at {" + input.getPath() + "} start");
        	
            Response response = null;
            
            try {
            	response = RuntimeConfig.getInstance().getReader().getRaw(input.getUrl(), timeout);
            }
            catch(Exception e) {
            	if(UnknownPicture == null)
            		UnknownPicture = RuntimeConfig.getInstance().getReader().getRaw(new URL("http://eacea.ec.europa.eu/img/icons/warning.jpg"), timeout);
            	response = UnknownPicture;
            }
            RuntimeConfig.getInstance().getWriter().write(response.bodyAsBytes(), input.getPath());
            output = input;
            System.err.println("TaskMediumWriter url{" + input.getUrl() + "} at {" + input.getPath() + "} end");
        } catch (Exception e) {
            e.printStackTrace();
            this.e = e;
        }
    }

}
